package com.cherrypt.api.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherrypt.api.core.dao.NoticeDao;
import com.cherrypt.api.model.dataobject.Notice;
import com.cherrypt.api.core.service.NoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, Notice> implements NoticeService {
    private static final Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);

    @Autowired
    private ListOperations<String, Object> listOperations;

    @Value("${api.config.redis.notice.value}")
    private String noticeValue;

    @Value("${api.config.redis.notice.exp}")
    private long noticeExp;

    @Override
    public List<Notice> getRedisNotice() {
        List<Notice> noticeList = new ArrayList<>();
        List<Object> list = listOperations.range(noticeValue, 0, -1);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                noticeList.add((Notice) o);
            }
        }
        noticeList.sort(Comparator.comparingLong(Notice::getModify).reversed());
        return noticeList;
    }

    @Override
    public void saveRedisNotice(List<Notice> noticeList) {
        noticeList.forEach(notice -> {
            listOperations.leftPush(noticeValue, notice);
        });
    }

    @Override
    public List<Notice> getNowNotice(int size) {
        List<Notice> noticeList = getRedisNotice();
        if (noticeList == null || noticeList.size() == 0) {
            noticeList = this.list(new QueryWrapper<Notice>()
                    .eq("is_show", true)
                    .orderByDesc("modify"));
            if (noticeList.size() != 0) {
                saveRedisNotice(noticeList);
                logger.info("缓存Notice到Redis, 有效公告条数: {}", noticeList.size());
            }
        }
        return noticeList;
    }
}
